﻿<%@ Page Language="C#" %>

<%@ Import Namespace="IRL.Utilities" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>

<script runat="server">
    public const int CURRENT_MODULE = 51;
    
    int pid;
    long ticks;
    string path;
    string strScript;
    bool HasWriteAccess = false;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        Security SysAcc = new Security(CURRENT_MODULE);
        // check is authenticate
        SysAcc.Authenticate();
        HasWriteAccess = SysAcc.IsAuthorized(2);
        
        if (Request.QueryString["pid"] != null)
        {
            // load reminder count        
            //Mics.loadReminderCount(lblReminderCount);
            
            pid = Convert.ToInt32(Request.QueryString["pid"]);
            path = ConfigurationSettings.AppSettings["CMS_Path"].ToString();
            path += @"\project_files\" + pid + @"\";
            if (HasWriteAccess)
            {
                strScript = "javascript:return confirm('Are you sure to remove the file?')";
            }
            else
            {
                strScript = "javascript:alert('You do not permission to perform this action.');return false";
            }
            
            if (!Page.IsPostBack)
            {
                headerInfo();
                rebind();
                // set back history
                ViewState.Add("BackStep", 0);
            }
            else
            {
                ViewState["BackStep"] = (int)ViewState["BackStep"] + 1;                
            }
            // cmdUpload client click event
            cmdUpload.Attributes.Add("onclick", "return upload('"+ HasWriteAccess +"');");
        }
    }

    void headerInfo()
    {        
        object connStr = ConfigurationSettings.AppSettings["sqlConn"];
        using (SqlConnection conn = new SqlConnection(connStr.ToString()))
        {
            SqlCommand cmd = new SqlCommand("sp_ProjectInfo", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@proposalid", SqlDbType.Int).Value = pid;
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                for (int i = 0; i < dr.FieldCount; i++)
                {
                    ViewState.Add(dr.GetName(i), dr[i]);
                }
                dr.Close();
                // get lookup
                ViewState["ClientName"] = Lookup.GetText("SELECT [Company_Name] FROM [tbl_Company_Info] WHERE [Company_ID]=" + ViewState["ClientID"].ToString(), conn);
                ViewState["ProjectType"] = Lookup.GetText("sp_Select_cms_Lookup 'project_type', " + ViewState["ProjectType"].ToString() + ", 1", conn);
                ViewState["ResearchType"] = Lookup.GetText("sp_Select_cms_Lookup 'research_type', " + ViewState["ResearchType"].ToString() + ", 1", conn);
                ViewState["ResearchCategory"] = Lookup.GetText("sp_Select_cms_Lookup 'research_category', " + ViewState["ResearchCategory"].ToString() + ", 1", conn);                
            }
        }
    }

    void rebind()
    {
        if (!HasWriteAccess)
        {
            divForm.Visible = false;
        }
        object connStr = ConfigurationSettings.AppSettings["sqlConn"];
        using (SqlConnection conn = new SqlConnection(connStr.ToString()))
        {
            //ViewState.Add("ProjectName", Lookup.GetText("SELECT [ProjectName] FROM [cms_Proposals] WHERE [ProposalID]=" + pid, conn));
            SqlCommand cmd = new SqlCommand("SELECT * FROM [cms_Files] WHERE [ProposalID]=" + pid + " ORDER BY [Ticks]", conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            // bound to datagrid
            grid1.DataSource = dr;
            grid1.DataBind();
            dr.Close();
        }
    }

    protected void cmdUpload_Click(object sender, EventArgs e)
    {
        HttpPostedFile uploadedFile = file1.PostedFile;
        string fileName;

        if (pid > 0 && HasWriteAccess)
        {
            if (uploadedFile != null && uploadedFile.ContentLength > 0)
            {
                fileName = UploadFile(uploadedFile);
                if (fileName != null)
                {
                    SaveRecord(fileName);
                    rebind();
                }
            }
        }
    }

    // UploadFile function
    protected string UploadFile(HttpPostedFile file)
    {
        string fileName = null;        
        int lastPos = file.FileName.LastIndexOf('\\');        

        fileName = file.FileName.Substring(++lastPos);        
        
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);            
        }
        ticks = DateTime.Now.Ticks;
        file.SaveAs(path + ticks + "_" + fileName);
        return fileName;
    }
    // SaveRecord
    protected void SaveRecord(string fileName)
    {
        object connStr = ConfigurationSettings.AppSettings["sqlConn"];
        using (SqlConnection conn = new SqlConnection(connStr.ToString()))
        {
            SqlCommand cmd = new SqlCommand("sp_SaveFile", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@proposalid", SqlDbType.Int).Value = pid;
            cmd.Parameters.Add("@filename", SqlDbType.NVarChar, 120).Value = fileName;
            cmd.Parameters.Add("@ticks", SqlDbType.BigInt).Value = ticks;
            conn.Open();
            cmd.ExecuteNonQuery();
            // show Status
            lblStatus.Text = "File is successfully uploaded.";
        }
    }

    protected void grid1_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        if (e.CommandName == "Remove")
        {
            if (HasWriteAccess)
            {
                RemoveFile(e.Item.Cells[1].Text, Convert.ToInt64(e.Item.Cells[0].Text));
                // set status
                lblStatus.Text = "File is successfully remove.";
            }
        }
        rebind();
    }
    
    // RemoveFile
    protected void RemoveFile(string fileName, long ticks)
    {
        string filePath = path + @"\" + ticks + @"_" + fileName;
        if (File.Exists(filePath))
        {
            File.Delete(filePath);
        }
        // Update database record
        object connStr = ConfigurationSettings.AppSettings["sqlConn"];
        using (SqlConnection conn = new SqlConnection(connStr.ToString()))
        {
            SqlCommand cmd = new SqlCommand("sp_DeleteFile", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@filename", SqlDbType.NVarChar, 120).Value = fileName;
            cmd.Parameters.Add("@ticks", SqlDbType.BigInt).Value = ticks;
            conn.Open();
            cmd.ExecuteNonQuery();
        }
    }

    protected void grid1_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            ImageButton bt;
            bt = (ImageButton)e.Item.Cells[4].Controls[1];
            if (bt != null)
            {
                bt.Attributes.Add("onclick", strScript);
            }
        }
    }
    
    // edit project
    string editProject()
    {
        string project_name = ViewState["ProjectName"].ToString();
        string project_code = ViewState["ProjectCode"].ToString();
        
        if (project_code == "")
        {
            return "<a class=\"edit\" href=\"saveProposal.aspx?pid=" + pid.ToString() + "\">" + project_name + "</a>";
        }
        else
        {
            return "<a class=\"edit\" href=\"saveProject.aspx?pid=" + pid.ToString() + "\">" + project_name + "</a>";
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="Description" content="Providing the tools and expertise needed to navigate in the emerging consumer markets of Indochina.">
    <meta name="keywords" content="Research in Indochina, Research Consultants in Indochina, Marketing Research in Indochina, Marketing Research Companies in Indochina, Marketing Consultants in Indochina Research in Vietnam, Research Consultants in Vietnam, Marketing Research in Vietnam, Marketing Research Companies in Vietnam, Marketing Consultants in Vietnam Research in Cambodia, Research Consultants in Cambodia, Marketing Research in Cambodia, Marketing Research Companies in Cambodia, Marketing Consultants in Cambodia Research in Laos, Research Consultants in Laos, Marketing Research in Laos, Marketing Research Companies in Laos, Marketing Consultants in Laos">
    <meta name="robots" content="all">

    <title>Indochina Research</title>
    <link rel="SHORTCUT ICON" href="../irl.ico" type="image/x-icon" />
    <link href="../css/global.css" rel="stylesheet" type="text/css" />
    <link href="css/cms.css" rel="stylesheet" type="text/css" />
        
    <script language="javascript">
        function upload(v){
            if(v=='True'){
                var f = document.DataForm;
                var status = document.getElementById("lblStatus");
                
                // Check file
                if(f.file1.value.length==0)
                {                
                    alert("Please click browse button to select file.");                
                    return false;
                }
                
                status.innerHTML = "Please wait while <b>uploading</b> file...";
                // form submit
                return true;
            }
            else
            {
                alert("You do not have permission to perform the action.");
                return false;
            }
        }
                
    </script>
</head>
<body>
<table width="773" border="0" cellspacing="0" cellpadding="0" align="center">
	<tr>
		<td width="765" height="540" align="center" valign="top" style="border:solid 1px #10147e;" >
			<!-- header -->
			<table border="0" cellpadding="0" cellspacing="0" width="100%">
				<tr bgcolor="#F4F4F9">
					<td colspan="3" align="right" style="padding:10px;">
						<b class="blueL">Client Management System</b>
					</td>
				</tr>
				<tr>
					<td class="wave_l">&nbsp;</td>
					<td><img src="images/wave_logo.jpg" width="107" height="83"></td>
					<td class="wave_r">&nbsp;</td>
				</tr>
				<tr>
					<td colspan="3" style="padding:0 20px;">
						<div style="background-color:#bcb3d5; padding:5px 10px;">
							<span style="float:right">
							    <a class="blue" href="javascript:history.go(-<%=(int)ViewState["BackStep"]+1 %>);">&laquo; Back</a>
							</span>
							<span class="pathmap">
								<a href="default.aspx" >CPanel</a> :: 
								<a href="default2.aspx" >Ops Files</a> :: Associated Files
						  </span>
						</div>
						<br />
						
						
					</td>
				</tr>
				
			</table>
			
			<!-- body -->
			<form id="DataForm" method="post" runat="server">
			<table border="0" width="100%" cellspacing="0" cellpadding="0">
				<tr>
					<td align="center" valign="top" style="padding-left:20px;">
						<table border="0" cellspacing="0" cellpadding="5" align="center" >
                            <tr>
                                <td align="right">Project name: </td>
                                <td class="blueL"><%=editProject() %></td>
                                <td width="40">&nbsp;</td>
                                <td align="right">Client name: </td>
                                <td class="blueL"><%=ViewState["ClientName"].ToString() %></td>
                            </tr>
                            <tr>
                                <td align="right">Project type: </td>
                                <td class="blueL"><%=ViewState["ProjectType"].ToString() %></td>
                                <td width="40">&nbsp;</td>
                                <td align="right">Project code: </td>
                                <td class="blueL"><%=ViewState["ProjectCode"].ToString() %></td>
                            </tr>
                            <tr>
                                <td align="right">Research type: </td>
                                <td class="blueL"><%=ViewState["ResearchType"].ToString() %></td>
                                <td width="40">&nbsp;</td>
                                <td align="right">Research category: </td>
                                <td class="blueL"><%=ViewState["ResearchCategory"].ToString() %></td>
                            </tr>
                            <tr>
                                <td colspan="5">&nbsp;
                                    
                                </td>
                            </tr>
                        </table>
                        <!-- Form -->
                        <div align="center">
                            <div id="divForm" class="divInfo" runat="server">
                                <fieldset>
                                    <legend><b style="font-size:7pt;">Add file &nbsp; </b></legend>
                                    <table border="0" cellspacing="0" cellpadding="6">
                                        <tr>
                                            <td colspan="5">
                                                <div align="center">
                                                    <asp:Label CssClass="orange" ID="lblStatus" runat="server" />
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>&nbsp;</td>
                                            <td><asp:Button ID="cmdUpload" Text="Upload" runat="server" OnClick="cmdUpload_Click" /></td>
                                            <td>&nbsp;</td>
                                            <td><input type="file" id="file1" size="50" runat="server" /></td>
                                            <td>&nbsp;</td>
                                        </tr>
                                    </table>
                                </fieldset>
                            </div>
                            <br />
                        </div>
                        <!-- Data Grid -->
                        <asp:DataGrid ID="grid1" HorizontalAlign="center" runat="server" CellSpacing="1"
                            CellPadding="5" BorderWidth="0" GridLines="none" AutoGenerateColumns="false"
                            OnItemCommand="grid1_ItemCommand" OnItemDataBound="grid1_ItemDataBound">
                            <HeaderStyle BackColor="#bcb3d5" Font-Size="7.5pt" ForeColor="white" Font-Bold="true" />
                            <ItemStyle BackColor="#efefef" />
                            <AlternatingItemStyle BackColor="white" />
                            <Columns>
                                <asp:BoundColumn Visible="false" DataField="Ticks" />
                                <asp:BoundColumn Visible="false" DataField="Filename" />
                                
                                <asp:TemplateColumn HeaderText="No">
                                    <HeaderStyle Width="20" />
                                    <ItemTemplate>
                                        <%# Container.ItemIndex+1%>
                                    </ItemTemplate>
                                </asp:TemplateColumn>
                                <asp:TemplateColumn HeaderText="Filename">
                                    <HeaderStyle Width="400" />
                                    <ItemTemplate>
                                        <a class="blue" href="download.aspx?pid=<%=pid %>&filename=<%# Server.UrlEncode(DataBinder.Eval(Container.DataItem, "Filename").ToString()) %>&salt=<%# DataBinder.Eval(Container.DataItem, "Ticks").ToString() %>"
                                            title="Download">
                                            <%# DataBinder.Eval(Container.DataItem, "Filename").ToString() %>
                                        </a>
                                    </ItemTemplate>
                                </asp:TemplateColumn>
                                <asp:TemplateColumn HeaderText="Remove">
                                    <HeaderStyle Width="40" HorizontalAlign="center" />
                                    <ItemStyle Width="40" HorizontalAlign="center" />
                                    <ItemTemplate>
                                        <asp:ImageButton ID="cmdRemove" CommandName="Remove" ImageUrl="images/delete.gif"
                                            runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateColumn>
                            </Columns>
                        </asp:DataGrid>
					</td>
				</tr>
			</table>
			</form>
			
		</td>
		
		<td width="6" class="rightShadow" valign="top">
			<img src="images/white.gif" width="6" height="6" /></td>
	</tr>
	
	<!-- bottom shadow -->
	<tr>
		<td height="6" class="bottomShadow">
			<img src="images/white.gif" width="6" height="6" /></td>
		
		<td width="6" height="6">
			<img src="images/shadow_corner.gif" width="6" height="6" /></td>
	</tr>
</table>



</body>
</html>
